﻿using System.Web;
using System.Web.Security;
using umbraco;
using uREST.Core.Resources;
using uREST.Core.Util;

namespace uREST.Core.Extensions
{
    public static class TokenExtensions
    {
        public static string Tokenize(this Token request)
        {
            return request.Tokenize(true);
        }

        public static string Tokenize(this Token request, bool encodePassword)
        {
            if (encodePassword)
            {
                var passwordFormat = request.Type == TokenType.User
                                           ? Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].PasswordFormat
                                           : Membership.Provider.PasswordFormat;

                request.Password = new MembershipHelper().EncodePassword(request.Password, passwordFormat);
            }

            var remoteAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDRESS"];
            var tokenKey = request.Username + "$" + request.Password + "$" + request.Type + "$" + remoteAddress;
            var hashedToken = tokenKey.Sha1Hash();

            return hashedToken;
        }
    }
}
